import type { FormInst, StepsProps } from 'naive-ui'
import type { Ref } from 'vue'
import type { NvFormProps } from './types'
import type { RowData } from '@/types'

export function useActions(
  props: NvFormProps,
  formRef: Ref<FormInst | undefined>,
  formData: Ref<RowData>,
  loading: Ref<boolean>,
  current: Ref<number>,
  status: Ref<StepsProps['status']>,
) {
  const validate: FormInst['validate'] = (...args) => {
    return formRef.value!.validate(...args)
  }

  const restoreValidation: FormInst['restoreValidation'] = () => {
    formRef.value!.restoreValidation()
    status.value = 'process'
  }

  function clear() {
    for (const key in formData.value) {
      if (formData.value[key] === null || formData.value[key] === undefined) {
        Reflect.deleteProperty(formData.value, key)
      }
      else {
        formData.value[key] = null
      }
    }
    restoreValidation()
  }

  async function submit() {
    try {
      await validate()
    }
    catch (err) {
      status.value = 'error'
      throw err
    }
    loading.value = true

    props.onSubmit?.(() => loading.value = false)
  }

  function prevStep() {
    status.value = 'process'
    current.value--
  }

  async function nextStep() {
    try {
      await validate()
    }
    catch (err) {
      status.value = 'error'
      throw err
    }
    status.value = 'process'
    current.value++
  }

  return {
    validate,
    restoreValidation,
    clear,
    submit,
    prevStep,
    nextStep,
  }
}

export type UseActionsReturn = ReturnType<typeof useActions>
